package com.winter.boot;


import com.winter.boot.context.ApplicationContext;
import com.winter.boot.context.DefaultApplicationContext;
import com.winter.boot.event.EventBroadcaster;
import com.winter.boot.web.Server;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

public class WinterApplication {

    private Set<Class<?>> primarySources;
    private EventBroadcaster eventBroadcaster;
    private static ApplicationContext applicationContext;

    public static ApplicationContext run(Class<?> primarySources, String... args) {
        return new WinterApplication(new Class[]{primarySources}).run(args);
    }

    public WinterApplication(Class<?>[] primarySources) {
        if (primarySources != null) {
            this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        }
    }

    public ApplicationContext run(String... args) {

        // TODO: 2022/10/19 监听器初始化环境/参数

        //context初始化
        ApplicationContext context = new DefaultApplicationContext(primarySources);
        applicationContext = context;
        try {
            context.refresh();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        //启动服务器
        Server server = Server.getServer();
        server.start();
        return context;
    }

    public void setEventBroadcaster(EventBroadcaster eventBroadcaster) {
        this.eventBroadcaster = eventBroadcaster;
    }

    public EventBroadcaster getEventBroadcaster() {
        return eventBroadcaster;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
